from flask import request, redirect, g
from application import app
from common.models.user import User
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager
from common.libs.Logs import UserLogs
import re

@app.before_request
def before_request():
    """拦截器"""

    path = request.path
    back_url = UrlManager.buildUrl('/user/login')

    if '/api' in path:
        return None

    # 忽略拦截的路由
    ignore_urls = app.config['IGNORE_URLS']
    url_pattern = re.compile('|'.join(ignore_urls))
    if url_pattern.match(path):
        return None

    # 忽略拦截的静态路由等
    ignore_check_urls = app.config['IGNORE_CHECK_URLS']
    ignore_check_pattern = re.compile('|'.join(ignore_check_urls))
    if ignore_check_pattern.match(path):
        return None

    # 执行登录校验
    user = check_login()
    g.current_user = None
    if user:
        g.current_user = user
    if not user:
        return redirect(back_url)

    # 添加用户访问日志
    UserLogs.access_log()
    return None

def check_login():
    """登录校验"""
    auth_cookie_info = request.cookies.get(app.config['AUTH_COOKIE_NAME'])
    if not auth_cookie_info:
        return False
    user_info = auth_cookie_info.split('#')
    if len(user_info) != 2:
        return False
    try:
        user = User.query.filter_by(uid=user_info[1]).first()
    except Exception:
        return False
    else:
        if user.status == 0:
            return False

    if UserService.geneAuthCode(user) != user_info[0]:
        return False

    return user
